# -*- coding = utf-8 -*-
# @Time : 2023/5/4 16:42
# @Author : 龙王赘婿_彪少
# @File : leisai_motor.py
# @Software: PyCharm

# 功能：雷赛电机一体化控制
# 波特率：115200
# 站号：0x01 0x02

import serial
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu

PORT = "com17"
baudrate = 9600
M1 = 0x01   # 电机1


class Motor:
    def __init__(self):
        self.master = modbus_rtu.RtuMaster(
            serial.Serial(port=PORT, baudrate=baudrate, parity='N', stopbits=1, xonxoff=0))
        self.master.set_timeout(1.0)
        # self.speed_run()
        self.stop()



    def read_holding_resasters(self, motor, addr, number) -> tuple:
        try:
            res = self.master.execute(motor, cst.READ_HOLDING_REGISTERS, starting_address=addr, quantity_of_x=number)
            return res
        except Exception as err:
            print("异常：", err)

    def write_single_register(self, motor, addr, value):
        try:
            res = self.master.execute(motor, cst.WRITE_SINGLE_REGISTER, starting_address=addr, output_value=value)
            # print(res)
        except Exception as err:
            print("异常：", err)

    def write_mutiple_registers(self, motor, addr, value_tuple):
        try:
            # print(value_tuple, type(value_tuple))
            res = self.master.execute(motor, cst.WRITE_MULTIPLE_REGISTERS, starting_address=addr, output_value=value_tuple)
            # print(res)
        except Exception as err:
            print("异常：", err)

    def speed_run(self):
        self.write_single_register(M1, 0x6200, 2)       # 配置模式
        self.write_single_register(M1, 0x6203, 120)     # 配置速度
        self.write_single_register(M1, 0x6204, 0x0032)  # 加速度
        self.write_single_register(M1, 0x6205, 0x0032)  # 减速度
        self.write_single_register(M1, 0x6002, 0x0010)  # 触发运行

    def stop(self):
        self.write_single_register(M1, 0x6002, 0x0040)  # 急停


if __name__ == "__main__":
    mot = Motor()
